package com.csmht.tododemo.aspect;

import com.csmht.tododemo.annotation.RoleIntercept;
import com.csmht.tododemo.constant.MessageConstant;
import com.csmht.tododemo.exiception.BaseException;
import com.csmht.tododemo.pojo.enumeration.RoleEnum;
import com.csmht.tododemo.until.BaseUnit;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Aspect
@Component
@Slf4j
public class RoleAspect {


    @Pointcut(value = "(@within(roleIntercept) || @annotation(com.csmht.tododemo.annotation.RoleIntercept))  && " +
            "within(com.csmht.tododemo.controller..*)", argNames = "roleIntercept")
    public void rolePointCut(RoleIntercept roleIntercept) {}

    @Before(value = "rolePointCut(roleIntercept)", argNames = "joinPoint,roleIntercept")
    public void RolePointCut(JoinPoint joinPoint, RoleIntercept roleIntercept) {

        RoleEnum role = BaseUnit.getCurrentRole().getRole();

        RoleIntercept annotation = joinPoint.getClass().getAnnotation(RoleIntercept.class);

        RoleEnum[] roles = annotation == null?roleIntercept.roles():annotation.roles();

        if(Arrays.stream(roles).noneMatch(r -> r == role)){
            throw new BaseException(MessageConstant.NO_ROLE);
        }
    }

}
